library(ISwR)

##################
#combine plot   ##
##################

x <- rnorm(1000000)
h <- hist(x, plot=F)
ylim <- range(0, h$density, dnorm(0))
xlim <- range(-3, 3)
hist(x, freq=F, ylim=ylim, xlim=xlim)
curve(dnorm(x), add = T)

##################
#group data	    ##
##################

energy

(lean <- energy$expend[energy$stature == "lean"])
(obese <- energy$expend[energy$stature == "obese"])

re <- split(energy$expend, energy$stature)

##################
#loops	    ##
##################

(x <- seq(0, 1, 0.05))
plot(x, x, ylab = "y", type = "l") #45 degree line
for(j in 2:30) 
{
	lines(x, x^j)
}

##################
#apply function ##
##################

thuesen

lapply(thuesen, mean, na.rm = T)
sapply(thuesen, mean, na.rm = T)

#rnorm is the random generation for the normal  distribution
m <- matrix(rnorm(12), 4) 
apply(m, 2, min) #2 indicates columns

energy
tapply(energy$expend, energy$stature, median)

#w <- read.csv(file.choose(), header = T, sep = "\t")
setwd("...")
w <- read.csv("worms.txt", header = T, sep = "\t")

tapply(w$Soil.pH, list(w$Vegetation, w$Damp), max)
table(w$Vegetation, w$Damp)

##################
#sorting	    ##
##################

intake
intake$post
sort(intake$post)

o <- order(intake$post)
o
intake$post[o]
intake[o,]

##################
#attach	    ##
##################

plot(thuesen$blood.glucose, thuesen$short.velocity)
attach(thuesen)
plot(blood.glucose, short.velocity)
search()

detach()
search()

##################
#subset	    ##
##################

thuesen

thue2 <- subset(thuesen, blood.glucose < 7)
thue2

thue3 <- transform(thuesen, log.gluc = log(blood.glucose))
thue3

thue4 <- within(thuesen, {
		log.gluc <- log(blood.glucose)
		m <- mean(log.gluc)
		centered.log.gluc <- log.gluc - m
		rm(m)
})
thue4










